import 'dart:convert';
import 'package:after_sale_plugin/package_event.dart';
import 'package:after_sale_plugin/pages/edit_order/cell/check_vehicle_error_item.dart';
import 'package:after_sale_plugin/pages/edit_order/cell/report_edit_item_cell.dart';
import 'package:after_sale_plugin/pages/edit_order/controller.dart';
import 'package:after_sale_plugin/pages/models/vehicle_model.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'package:wechat_assets_picker_plus/wechat_assets_picker_plus.dart';

import '../../constant.dart';

class EditOrderView extends BaseGetView<EditOrderController> {
  @override
  String get title => AppLanguageUtil.to.editOrderNavTitle;

  @override
  Color? get barBackgroundColor => Colors.black;

  @override
  Widget? get backView => CommonWidgets.appBarLeading(
        onTap: () {
          if (controller.state.reportOrderInfo.reportVehicleName.isNotEmpty ||
              controller.state.reportOrderInfo.sn.isNotEmpty ||
              controller.state.reportOrderInfo.reportPersonName.isNotEmpty ||
              controller.state.reportOrderInfo.reportPhoneNumber.isNotEmpty ||
              controller.state.reportOrderInfo.reportTypeDesc.isNotEmpty ||
              controller.state.reportOrderInfo.problemContent.isNotEmpty ||
              controller.state.reportOrderInfo.assetModels
                  .where((p0) => !p0.isAdd)
                  .isNotEmpty) {
            // 是否保存正在编辑的订单
            PackageEvent.showConfirmAlert(
              AppLanguageUtil.to.whetherToSaveReportOrderPrompts,
              confirmTitle: AppLanguageUtil.to.titleSave,
              cancelTitle: AppLanguageUtil.to.titleNotSave,
              confirmCallBack: (p0) {
                if (p0) {
                  // 保存编辑订单
                  SharedPreferencesService.to
                      .setString(EDIT_ORDER_INFO,
                          controller.state.reportOrderInfo.toJson())
                      .then((value) {
                    Get.back();
                  });
                } else {
                  Get.back();
                }
              },
            );
          } else {
            Get.back();
          }
        },
      );

  @override
  Widget buildBody(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: ListView(
        children: [
          // 报修车型
          ReportEditItem(
            ReportCellType.arrow,
            InputType.text,
            AppLanguageUtil.to.titleReportVehicleType,
            AppLanguageUtil.to.titleReportVehicleTypePlacehodler,
            controller.state.reportOrderInfo.reportVehicleName,
            onTap: (t, a) {
              PackageEvent.selectVehicle((p0) {
                VehicleDataModel vehicleDataModel =
                    VehicleDataModel.fromMap(p0);
                vehicleDataModel.isConnected = false;
                controller.state.reportOrderInfo.sn = vehicleDataModel.sn ?? "";
                controller.state.reportOrderInfo.reportVehicleName.value =
                    vehicleDataModel.name.value;
              });
            },
          ),
          // 报修人姓名
          Obx(
            () => Visibility(
              visible: controller.state.isChineseRegion.value,
              child: ReportEditItem(
                ReportCellType.textFeild,
                InputType.text,
                AppLanguageUtil.to.titleReportPersonName,
                AppLanguageUtil.to.titleReportPersonNamePlacehodler,
                controller.state.reportOrderInfo.reportPersonName,
                callbackTextFeildValue: (p0) {
                  controller.state.reportOrderInfo.reportPersonName = p0.obs;
                  controller.state.booleansMap[
                      AppLanguageUtil.to.titleReportPersonName] = p0.isNotEmpty;
                },
              ),
            ),
          ),
          // 联系电话
          Obx(
            () => ReportEditItem(
              ReportCellType.text,
              controller.state.isChineseRegion.value
                  ? InputType.phone
                  : InputType.email,
              controller.state.isChineseRegion.value
                  ? AppLanguageUtil.to.titleReportPersonNumber
                  : AppLanguageUtil.to.titleReportPersonEmail,
              controller.state.isChineseRegion.value
                  ? AppLanguageUtil.to.titleReportPersonNumberPlacehodler
                  : AppLanguageUtil.to.titleReportPersonEmailPlacehodler,
              controller.state.reportOrderInfo.reportPhoneNumber,
              callbackTextFeildValue: (p0) {
                controller.state.reportOrderInfo.reportPhoneNumber = p0.obs;
                controller.state.booleansMap[
                    AppLanguageUtil.to.titleReportPersonNumber] = p0.isNotEmpty;
              },
            ),
          ),
          // 报修类型
          ReportEditItem(
            ReportCellType.arrow,
            InputType.text,
            AppLanguageUtil.to.titleReportType,
            AppLanguageUtil.to.titleReportTypePlacehodler,
            controller.state.reportOrderInfo.reportTypeDesc,
            onTap: (t, a) {
              List<String> names = [];
              for (var i = 0; i < controller.state.reportTypes.length; i++) {
                names.add(controller.state.reportTypes[i].title);
              }
              LxBottomSheet.show(
                Get.context!,
                dataArr: names,
                title: AppLanguageUtil.to.titleReportType,
                selectedCallback: (index, text) {
                  int rawValue = index > 6 ? 0 : index + 1;
                  controller.state.reportOrderInfo.reportType.value = rawValue;
                  controller.state.reportOrderInfo.reportTypeDesc.value =
                      (ReportType.getTypeByNum(rawValue) ?? ReportType.other)
                          .title;
                  controller.state
                          .booleansMap[AppLanguageUtil.to.titleReportType] =
                      text?.isNotEmpty;
                },
              );
            },
          ),
          // 问题描述
          ReportEditItem(
            ReportCellType.textView,
            InputType.text,
            AppLanguageUtil.to.titleProblemDesc,
            AppLanguageUtil.to.titleProblemDescPlacehodler,
            controller.state.reportOrderInfo.problemContent,
            bgHeight: 130,
            maxLength: 1000,
            callbackTextFeildValue: (p0) {
              controller.state.reportOrderInfo.problemContent = p0.obs;
              controller
                      .state.booleansMap[AppLanguageUtil.to.titleProblemDesc] =
                  p0.isNotEmpty;
            },
          ),
          // 图片/视频
          ReportEditItem(
            ReportCellType.assets,
            InputType.text,
            AppLanguageUtil.to.titleUploadPhoptoAndVideo,
            null,
            ''.obs,
            bgHeight: 110,
            onTap: (type, model) {
              FocusScope.of(context).unfocus();
              switch (type) {
                case ItemOnTapType.addMedia:
                  PackageEvent.selectAsssets(
                    (p0) {
                      // 添加资源文件
                      AssetModel assetModel =
                          AssetModel.fromMap(jsonDecode(p0));
                      bool isFull =
                          controller.state.reportOrderInfo.assetModels.length >=
                              9;
                      // 删除 ‘+’
                      if (isFull) {
                        controller.state.reportOrderInfo.assetModels
                            .removeLast();
                      }
                      controller.state.reportOrderInfo.assetModels.insert(
                        controller.state.reportOrderInfo.assetModels.length -
                            (isFull ? 0 : 1),
                        assetModel,
                      );
                      // 上传资源文件
                      PackageEvent.uploadAsssets(
                        (fileName) {
                          AssetModel tempModel = assetModel
                            ..src = AssetModel.getUrl(OSS_FILE_URL, fileName);
                          for (var i = 0;
                              i <
                                  controller
                                      .state.reportOrderInfo.assetModels.length;
                              i++) {
                            if (controller.state.reportOrderInfo.assetModels[i]
                                    .filePath ==
                                tempModel.filePath) {
                              controller.state.reportOrderInfo.assetModels[i] =
                                  tempModel;
                            }
                          }
                        },
                        param: assetModel.filePath,
                      );
                    },
                    param: 9 -
                        controller.state.reportOrderInfo.assetModels.length +
                        1,
                  );
                  break;
                case ItemOnTapType.deleteMedia:
                  controller.state.reportOrderInfo.assetModels.remove(model);
                  if (!controller
                      .state.reportOrderInfo.assetModels.last.isAdd) {
                    controller.state.reportOrderInfo.assetModels
                        .add(AssetModel.add);
                  }
                  break;
                default:
                  break;
              }
            },
            assetModels: controller.state.reportOrderInfo.assetModels,
          ),
          CheckVehicleErrorItem(
            reportOrderInfo: controller.state.reportOrderInfo.obs,
            onTap: controller.startCheckErrAction,
            highlighting: controller.state.bleConnected,
            isShowCheckedResult: controller.state.isCheckedErr,
          ),
          Obx(
            () => Padding(
              padding: const EdgeInsets.symmetric(horizontal: 12),
              child: LxButton(
                title: AppLanguageUtil.to.titleSubmitReport,
                onTap: controller.submitAction,
                height: 44,
                buttonStausEnum: controller.state.allowedSubmit.value
                    ? ButtonStausEnum.normal
                    : ButtonStausEnum.disable,
              ),
            ),
          ),
          SizedBox(height: screenBottom == 0 ? 20 : screenBottom),
        ],
      ),
    );
  }
}
